"""
智能AI助手API 调试版
"""
from typing import Union

from pydantic import BaseModel
from .llm.agent_config import run_agent
from fastapi import APIRouter
from db.db_work import MysqlLite
import json

router = APIRouter()

class Question_data(BaseModel):
    user_id: int
    date: str
    data: list
    id : Union[int, None]=None


@router.post("/ai-test/chat")
async def chat_with_ai(query: dict):
    print(query)
    return await run_agent(query["query"])
#添加问答记录
@router.post("/ai-test/add_column")
def add_column(data1: Question_data):
    print(data1)
    user_id = data1.user_id
    date = data1.date
    data = data1.data
    data_str = json.dumps(data, ensure_ascii=False)
    mysql=MysqlLite()
    mysql.operation_sql("create table if not exists history_ai (ID integer primary Key AUTOINCREMENT,date_ TEXT DEFAULT CURRENT_TIMESTAMP,data_ text,user_id INTEGER,FOREIGN KEY (user_id) REFERENCES user_info(ID) ON DELETE CASCADE)")
    mysql.operation_sql("insert into history_ai (date_,data_,user_id) values (?,?,?)",(date,data_str,user_id))
    return 'ok'
#获取问答记录
@router.get("/ai-test/get_history")
def get_history(user_id : int):
    mysql=MysqlLite()
    lis=mysql.select_sql("select * from history_ai where user_id=?",(user_id,))
    if lis:
        for i in range(len(lis)):
            lis[i][2] = json.loads(lis[i][2] )

        return {
            'code': 200,
            'data': lis
        }
    else:
        return {
            'code': 200,
            'data': []
        }
#修改问答记录
@router.put("/ai-test/update_ai_chain")
def update_ai_chai(data1: Question_data):
    date = data1.date
    data = data1.data
    id = data1.id
    data_str = json.dumps(data, ensure_ascii=False)
    mysql = MysqlLite()
    mysql.operation_sql(
        "create table if not exists history_ai (ID integer primary Key AUTOINCREMENT,date_ TEXT DEFAULT CURRENT_TIMESTAMP,data_ text,user_id INTEGER,FOREIGN KEY (user_id) REFERENCES user_info(ID) ON DELETE CASCADE)")
    mysql.operation_sql("update history_ai set date_=?,data_=? where ID = ?", (date, data_str, id))
    return 'ok'



